let accountUtils =require("./accountUtils");

let Tx = require('ethereumjs-tx');
let transaction={
  from:'',
  to:'',
  value:'',
  gas:'',
  gasPrice:'',
  nonce:'',
  data:''
}

let getTransaction= async (web3,from,to,value,gas,gasPrice,nonce,data)=>{
if(nonce){
    web3.eth.sendTransaction({
        from: from,
        to: to,
        value: value,
        gas:gas,
        gasPrice:gasPrice,
        nonce:nonce,
        data:data
    }).on('transactionHash', function(hash){
            console.log(hash)
    }).on('receipt', function(receipt){
        console.log('交易成功:'+receipt)
    }).on('error', function(error){
        console.log(error)
    }).on('confirmation', function(confirmationNumber, receipt){
        console.log(confirmationNumber)
        console.log(receipt)
    })
}else{
        web3.eth.getTransactionCount(from).then((accountNonce)=>{
                let string='测试一下';
                web3.eth.sendTransaction({
                    from: '0x76534eE11bBe5127Dca27D39037588c82f256604',
                    to: '0x27fE8679D8B60bC264477899155F49A453819AFd',
                    value: '1000000000000000',
                    gas:'3000000',
                    gasPrice:'10000000',
                    nonce:accountNonce,
                    data:data
                }).on('transactionHash', function(hash){
                        console.log(hash)
                }).on('receipt', function(receipt){
                    console.log('交易成功:'+receipt)
                }).on('error', function(error){
                    console.log(error)
                }).on('confirmation', function(confirmationNumber, receipt){
                    console.log(confirmationNumber)
                    console.log(receipt)
                })
        }), (error)=>{
            console.log(error)
        }
    }
}

let getCoinContract= async (web3,abi,address)=>{
  let contract=await new web3.eth.Contract(abi,address);
  return contract;
}

let getCoinBalance= async (contract,account)=>{
   let balance=await contract.methods.balanceOf(account).call();
  return balance;
}
let getCoinDecimals= async (contract)=>{
  try {
    let decimals=await contract.methods.decimals().call();
    return decimals;
  }catch (e) {
    console.log(e)
    return 18;
  }

}

let getGasLimit= async (web3,to,data)=>{
 let limit=await web3.eth.estimateGas({
    to: to,
    data: web3.utils.toHex(data)
  })
  return limit;
}

let getGasPrice= async (web3)=>{
  return await web3.eth.getGasPrice();
}

let getTransactionCount=async (web3,address)=>{
  return await web3.eth.getTransactionCount(address);
}

let sendSignedTransaction=async (web3,nonce,gasPrice,gasLimit,priKey,to,value,data)=>{

  var rawTx = {
    nonce: nonce,
    gasPrice: web3.utils.toHex(gasPrice),
    gasLimit: gasLimit,
    to: to,
    value: value,
    data: web3.utils.toHex((data))
  }

  if(priKey.indexOf('0x')!=-1){
    priKey=priKey.substring(2,priKey.length)
  }
  var privateKey = Buffer.from(priKey, 'hex')
  var tx = new Tx(rawTx);
  tx.sign(privateKey);
  var serializedTx = tx.serialize();

      web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
        .on('transactionHash', function(hash){
          console.log('交易hash:'+hash)
        })
        // .on('receipt', function(receipt){
        //   console.log(receipt)
        //   web3.eth.getBalance('0x76534eE11bBe5127Dca27D39037588c82f256604').then((res)=>{
        //     console.log(res)
        //   })
        // })
        .on('confirmation', function(confirmationNumber, receipt) {
          console.log('确认号码:' + confirmationNumber)
        })
        .on('error', console.error);
}
// const Web3 = require('web3');
// const ethUtil = require('ethereumjs-util');
// const ethWallet = require('ethereumjs-wallet');
// const mnemonicProvider = require("truffle-hdwallet-provider");
//
//
// let web3 = new Web3(new mnemonicProvider('toddler copy giraffe elbow noise afraid midnight wealth exact sketch reject venue','https://mainnet.infura.io/v3/35a1594522af4c319fd0265d92293276'));
// getCoinContract(web3,[{"constant": true, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "approve", "outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "_from", "type": "address"}, {"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "transferFrom", "outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "decimals", "outputs": [{"name": "", "type": "uint8"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [{"name": "_owner", "type": "address"}], "name": "balanceOf", "outputs": [{"name": "balance", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [], "name": "symbol", "outputs": [{"name": "", "type": "string"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "transfer", "outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}, {"name": "_extraData", "type": "bytes"}], "name": "approveAndCall", "outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"name": "_owner", "type": "address"}, {"name": "_spender", "type": "address"}], "name": "allowance", "outputs": [{"name": "remaining", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"inputs": [{"name": "_initialAmount", "type": "uint256"}, {"name": "_tokenName", "type": "string"}, {"name": "_decimalUnits", "type": "uint8"}, {"name": "_tokenSymbol", "type": "string"}], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": true, "name": "_from", "type": "address"}, {"indexed": true, "name": "_to", "type": "address"}, {"indexed": false, "name": "_value", "type": "uint256"}], "name": "Transfer", "type": "event"}, {"anonymous": false, "inputs": [{"indexed": true, "name": "_owner", "type": "address"}, {"indexed": true, "name": "_spender", "type": "address"}, {"indexed": false, "name": "_value", "type": "uint256"}], "name": "Approval", "type": "event"}],'0x9ab165D795019b6d8B3e971DdA91071421305e5a').then((res)=>{
//
//   console.log(res)
//    getCoinBalance(res,'0x76534eE11bBe5127Dca27D39037588c82f256604').then((balance)=>{
//     console.log(balance)
//   })
// })

// module.exports={
//   getCoinContract,
//   getCoinBalance,
//   getGasLimit,
//   getGasPrice,
//   getTransactionCount,
//   sendSignedTransaction
// };
let convertBigNumber=(param)=>{
  let strParam = String(param)
  let flag = /e/.test(strParam)
  if (!flag) return param

  // 指数符号 true: 正，false: 负
  let sysbol = true
  if (/e-/.test(strParam)) {
    sysbol = false
  }
  // 指数
  let index = Number(strParam.match(/\d+$/)[0])
  // 基数
  let basis = strParam.match(/^[\d\.]+/)[0].replace(/\./, '')

  if (sysbol) {
    return basis.padEnd(index + 1, 0)
  } else {
    return basis.padStart(index + basis.length, 0).replace(/^0/, '0.')
  }
}
let web3Utils={
  getCoinContract,
  getCoinBalance,
  getCoinDecimals,
  getGasLimit,
  getGasPrice,
  getTransactionCount,
  sendSignedTransaction,
  convertBigNumber
};
export default web3Utils;
//module.exports=web3Utils;
